import { Injectable } from '@angular/core';
import { RequestService } from './request.service';
import { MenuModel } from '../../modules/dashboard/components/menu/menu.interface';

@Injectable()
export class MenuService {

    menuModels = new Array<MenuModel>();

    constructor(private request: RequestService) { }

    /**
     * 加载系统菜单
     */
    loadMenu(callback = new Function()): any {
        this.request.url('/managerapi/menu').subscribe(res => {
            this.menuModels = [];
            const menus = res.datas;
            menus.forEach(model => {
                const menuModel = {
                    modelTitle: model.title,
                    menuGroups: new Array<any>(),
                    active: false
                };
                model.menus.forEach(menu => {
                    const menuGroup: any = {
                        groupTitle: menu.title,
                        icon: menu.icon,
                        image: menu.image,
                        url: menu.url,
                        menuItems: new Array<any>(),
                        targetModel: menuModel,
                        active: false
                    };
                    menu.children.forEach(child => {
                        const menuItem: any = {
                            title: child.title,
                            url: child.url,
                            targetGroup: menuGroup,
                            active: false
                        };

                        menuGroup.menuItems.push(menuItem);
                    });
                    menuModel.menuGroups.push(menuGroup);
                });
                this.menuModels.push(menuModel);
            });
            // 默认选中第一个模块
            // tslint:disable-next-line:no-unused-expression
            this.menuModels[0] && (this.menuModels[0].active = true);
            callback();
        });
    }
}
